package sk.naive.talker.command;

import sk.naive.talker.MailHelper;
import sk.naive.talker.message.DefaultMessageFactory;

import javax.mail.*;
import java.rmi.RemoteException;
import java.io.IOException;
import java.util.*;

/**
 * Mail delete - deletes selected message.
 *
 * @author <a href="mailto:virgo@naive.deepblue.sk">Richard "Virgo" Richter</a>
 * @version $Revision: 1.5 $ $Date: 2007-05-07 10:34:20 $
 */
public class MailDelete extends AbstractCommand {
	public void exec()
		throws CommandException,
		RemoteException
	{
		try {
			if (params == null || params.length() == 0) {
				sendMisusageWarning();
				return;
			}
			Folder folder = ((MailHelper) getTalker().getProperties().get(MailHelper.TPROP_MAIL_HELPER)).getInbox(user);
			if (params.toLowerCase().indexOf('x') != -1) {
				folder.expunge();
				sendHelper().sendMessage(user, "mailDelete.expunged");
			} else {
				boolean delete = true;

				String[] sa = params.split(" ", 2);
				if (sa.length > 1) {
					if ("undelete".startsWith(sa[0].toLowerCase())) {
						delete = false;
					}
					params = sa[1];
				}
				BitSet deleted = new BitSetSelector().create(params, folder.getMessageCount());
				int deletedCount = 0;
				for (int i = 1; i <= folder.getMessageCount(); i++) {
					if (deleted.get(i)) {
						folder.getMessage(i).setFlag(Flags.Flag.DELETED, delete);
						deletedCount++;
					}
				}
				user.getProperties().put(DefaultMessageFactory.CTXKEY_VAL, String.valueOf(deletedCount));
				user.getProperties().put(DefaultMessageFactory.CTXKEY_VAL + 1, String.valueOf(folder.getMessageCount() - folder.getDeletedMessageCount()));
				if (delete) {
					sendHelper().sendMessage(user, "mailDelete.deleted");
				} else {
					sendHelper().sendMessage(user, "mailDelete.undeleted");
				}
			}
			folder.close(false);
		} catch (NumberFormatException e) {
			sendMisusageWarning();
		} catch (AuthenticationFailedException e) {
			sendHelper().sendMessage(user, "mail.authenticationFailed");
		} catch (IOException e) {
			sendHelper().sendMessage(user, "mail.ioError");
		} catch (MessagingException e) {
			throw new CommandException(e);
		}
	}
}
